package com.hkts.management.message.msg.sendUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hkts.management.common.vo.UserBasicInfoVo;
import com.hkts.management.message.fegin.IUserAppServiceClient;
import com.hkts.management.message.notification.SubscribeMessageVO;
import com.hkts.management.message.notification.WxMssVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.hkts.management.common.vo.RedisConstants.ACCESS_TOKEN;


@Component
public class MsgSendUtil {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserAppServiceClient userAppServiceClient;
    /**
     * 微信消息推送
     * @return
     */
    public String getAccessToken() {
        if (redisTemplate.opsForValue().get(ACCESS_TOKEN) != null ){
            System.out.println(redisTemplate.opsForValue().get(ACCESS_TOKEN));
            return (String) redisTemplate.opsForValue().get(ACCESS_TOKEN);
        }
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wx3e1d6f5c08a3aac7");
        params.put("APPSECRET", "b8e6c6441a3a26aaf3cbe5774483d544");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String Access_Token = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        redisTemplate.opsForValue().set(ACCESS_TOKEN,Access_Token,7140);
        return Access_Token;
    }
    /**
     * 发送微信消息
     * @param userId
     * @param msg
     */
    public void sendMessageByUserId(String userId, String msg) {
        //TODO 从mq获取的数据 调取权限方法 被重定向 如何处理
        UserBasicInfoVo hontUserTo = userAppServiceClient.remoteUserBasicInfo().getResult();
        if(ObjectUtils.isNotEmpty(hontUserTo)){
            throw new RuntimeException("用户信息有误");
        }
        if(hontUserTo.getOpenId()==null){
            throw new RuntimeException("司机无openId");
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        SubscribeMessageVO bean = new SubscribeMessageVO();
        SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(new Date());
        bean.setThing1(new SubscribeMessageVO.Thing1(msg));
        bean.setTime2(new SubscribeMessageVO.Time2(format));
        WxMssVo wxMssVO = new WxMssVo();
        wxMssVO.setTouser(hontUserTo.getOpenId());
        wxMssVO.setTemplate_id("eelhtBbVOfpyCU13R0paxTenquHq81IJRN6HX7tPOi8");//模板id号码
        wxMssVO.setData(bean);
        try {
            ResponseEntity<String> responseEntity =restTemplate.postForEntity(url, wxMssVO, String.class);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



}
